package com.balabala.gym_goods.dao.impl;

import com.balabala.api.UserFeignClient;
import com.balabala.constant.UserConstant;
import com.balabala.dto.UserInfoDto;
import com.balabala.goods.pojo.dto.CartItemDTO;
import com.balabala.gym_goods.dao.CartDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author 何涛
 * @Date: 2023/05/07/ 16:20
 * @description
 */
@Repository
@Slf4j
public class CartDaoImpl implements CartDao {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    HttpServletRequest request;
    @Autowired
    UserFeignClient userFeignClient;

    @Override
    public BoundHashOperations getUserCartOptions()
    {
        //获取用户信息
        UserInfoDto userInfo = userFeignClient.getUserInfoByUserToken(request.getHeader("user-token")).getData();

        return redisTemplate.boundHashOps(UserConstant.USER_CART + userInfo.getId());

    }

    @Override
    public void addSkuToCart(Long skuId, CartItemDTO cartItemDTO) {

        log.info("放入购物项到购物车,skuId:{},订单项：{}",skuId,cartItemDTO.toString());
        BoundHashOperations userCartOptions = getUserCartOptions();
        userCartOptions.put(skuId,cartItemDTO);
    }

    @Override
    public Boolean updateSkuToCart(Long skuId, CartItemDTO cartItemDTO) {
        log.info("修改订单项信息，skuId：{}，订单项：{}",skuId,cartItemDTO);
        addSkuToCart(skuId,cartItemDTO);
        return true;
    }

    @Override
    public List<CartItemDTO> getUserCartItemList() {
        return getUserCartOptions().values();
    }

    @Override
    public Boolean deleteUserCart() {
        return getUserCartOptions().expire(-1, TimeUnit.SECONDS);
    }

    @Override
    public Boolean deleteCartItemBySkuId(Long skuId) {
        return getUserCartOptions().delete(skuId)>0?true:false;
    }

    @Override
    public Map<Long, CartItemDTO> getUserCartEntries() {

        return getUserCartOptions().entries();
    }

    @Override
    public void batchUpdate(Map<Long, CartItemDTO> userCartMap) {
        getUserCartOptions().putAll(userCartMap);
    }

}
